#!/usr/bin/python
# Created by Juan C. Espinoza <jucar.espinoza@gmail.com> Feb 13, 2015

import os
import cPickle
import argparse
from joblib import Parallel, delayed
from lisn_utils import LISNRequest, GPSDateTime, timedelta, TECData, plotter 

INPUT = '/data1/gps/'
OUTPUT = '/data1/products/'

req = LISNRequest(debug=False)
sites = req.stations(instrument='gps')
    
def tecmap(date, args):
    '''
    '''
    ###read data
    print 'Creating TEC maps for %s' % date
    TEC = []
    for site in sites:
        if args.realtime:
            filename = os.path.join('/data/temp/realtime/%s.pkl' % site['code'])
        else:
            filename = os.path.join(INPUT, '%s/%s/%s/tec/%s_%s.dat' % (site['network'], 
                                                                          site['code'], 
                                                                          date.strftime('%Y/%m'),
                                                                          site['code'],
                                                                          date.strftime('%y%m%d')))        
        if not os.path.exists(filename): 
            continue

        if args.realtime:
            try:
                TEC.append(cPickle.load(open(filename)))                
            except:
                continue
        else:
            try:
                TEC.append(TECData(filename))                
            except:
                continue
    
    for j in range(args.numfig):
        dt = date+args.delta*60*j
        if args.realtime:
            figname = '/data/temp/realtime/tec_map_%s.png' % dt.strftime('%H%M')
        else:
            figname = os.path.join(OUTPUT, '%s/%s/tec_%s.png' % (args.type,
                                                                 dt.strftime('%Y/%m/%d'),
                                                                 dt.strftime('%y%m%d_%H%M'),))
        if not args.overwrite and os.path.exists(figname):
            continue
        
        plotter.plot_tec_map(TEC, dt, ptype=args.type, delta=args.delta, figname=figname, 
                             prns=args.prns, bad_prns=args.bad_prns, min_ele=args.min_ele)

def main():
    '''
    Script to generate tec plots in realtime from 15 min raw data
    '''
    parser = argparse.ArgumentParser(description=main.func_doc)
    # add options and arguments
    parser.add_argument('dates', nargs='*', default=[],
        help='Period of time to be processed (start and end date) fmt:yy,mm,dd')
    parser.add_argument('-N', '--nproc', action='store', default=8, type=int,
            help='stations four-char codes')
    parser.add_argument('-r', '--realtime', action='store_true', default=False,
            help='Create realtime map')
    parser.add_argument('-o', '--overwrite', action='store_true', default=False,
            help='Overwrite figures')
    parser.add_argument('-t', '--type', action='store', choices=['measured', 'fitted'],
            default='measured', help='Overwrite figures')
    parser.add_argument('-d', '--delta', action='store', default=60, type=int,
            help='Time delta in minutes')
    parser.add_argument('-n', '--numfig', action='store', default=24, type=int,
            help='Number of figures (maps)')
    parser.add_argument('-p', '--prns', action='store', default=None,
            help='List of PRN to be plotted')
    parser.add_argument('-b', '--bad_prns', action='store', default=None,
            help='List of PRN to be excluded')
    parser.add_argument('-e', '--min_ele', action='store', default=30, type=int,
            help='Mask values to elevation>min_ele')
    
    args = parser.parse_args()
    if len(args.dates)>0 :
        try:
            date_1 = GPSDateTime(args.dates[0])
            if len(args.dates) == 2:
                date_2 = GPSDateTime(args.dates[1])
            else:
                date_2 = date_1
        except:
            parser.error('Dates can not be parsed fmt: yyyy,mm,dd')
    else:
        if args.realtime:
            date_1 = GPSDateTime().replace(second=0, microsecond=0)-60*60
        else:
            date_1 = GPSDateTime().date()-timedelta(1)
        date_2 = date_1
    
    if args.prns is not None:
        args.prns = args.prns.split(',')
    if args.bad_prns is not None:
        args.bad_prns = args.bad_prns.split(',')
        
    dates = [date_1+60*60*24*x for x in range(int(date_2-date_1)/(60*60*24)+1)]
    Parallel(n_jobs=args.nproc)(delayed(tecmap)(dt, args) for dt in dates)
        
#Execute main routine
if __name__ == "__main__":
    dt = GPSDateTime()
    print '\n Start at %s' % dt.now()
    main()    
    print '\n Total secs: %s' % (GPSDateTime()-dt)